package com.tom.exception;

import com.tom.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobaExceptionHandler {
    @ExceptionHandler(GloblException.class)
    public AjaxResult globlExceptionHandler(Throwable e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder s = new StringBuilder();
        allErrors.forEach(error->{
            s.append(error.getDefaultMessage()).append(";");
        });

        return AjaxResult.me().setSuccess(false).setMessage(s.toString());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Throwable e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("后端系统异常");
    }


}
